package com.first.run.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.first.run.constant.SysConstants;
import com.first.run.entity.SysUser;
import com.first.run.service.SysUserService;
import com.first.run.utils.PasswordHelper;
import com.first.run.vo.UserInfo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealmConfig extends AuthorizingRealm {
    @Autowired
    private SysUserService userService;

    /**
     * 获取授权信息
     * @param principalCollection
     * @return
     */
    @Override
     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("获取授权信息");
        //添加角色权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //获取登录的用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        //根据用户名查询用户信息
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
        //通过用户信息 查询用户的角色和权限
        UserInfo userInfo = userService.getUserInfo(user);

        //添加角色
        for (Integer role : userInfo.getRoles()) {
            authorizationInfo.addRole(role.toString());
        }
        //添加权限
        for (String permission : userInfo.getPermissions()) {
            authorizationInfo.addStringPermission(permission);
        }
        return authorizationInfo;
    }

    /**
     * 获取身份验证信息
     * Shiro中，最终是通过 Realm 来获取应用程序中的用户、角色及权限信息的。
     *
     * @param authenticationToken 用户身份信息 token
     * @return 返回封装了用户信息的 AuthenticationInfo 实例
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        System.out.println("先走login接口 在执行该身份验证   2.获取身份验证信息 = ");
        String username = (String) authenticationToken.getPrincipal();
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
        if (user == null) {
            throw new UnknownAccountException(SysConstants.unknownAccount);
        }
        //DisabledAccountException      账号未启用
        //IncorrectCredentialsException     密码错误

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()), getName());

        return authenticationInfo;
    }
}
